package com.infra.micro.oss.domain.repository;

import com.infra.micro.oss.domain.db.entity.FileInfoExample;
import com.infra.micro.oss.domain.db.entity.FileInfoPO;
import com.infra.micro.oss.domain.db.mapper.FileInfoMapper;
import com.infra.micro.oss.model.req.QueryFileInfoReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class FileInfoRepository {
    @Resource
    private FileInfoMapper fileInfoMapper;

    public FileInfoPO queryBySHA(String sha) {
        FileInfoExample example = new FileInfoExample();
        example.createCriteria().andShaEqualTo(sha);
        return fileInfoMapper.selectByExample(example).stream().findFirst().orElse(null);
    }

    public FileInfoPO queryByFileId(Long fileId) {
        return fileInfoMapper.selectByPrimaryKey(fileId);
    }

    public List<FileInfoPO> queryByFileIds(List<Long> fileIds) {
        FileInfoExample example = new FileInfoExample();
        example.createCriteria().andFileIdIn(fileIds);
        return fileInfoMapper.selectByExample(example);
    }

    public List<FileInfoPO> queryByCond(QueryFileInfoReq req) {
        FileInfoExample example = new FileInfoExample();
        FileInfoExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(req.getMimeType())) {
            criteria.andMimeTypeEqualTo(req.getMimeType());
        }

        if (req.getStartDate() != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(req.getStartDate());
        }

        if (req.getEndDate() != null) {
            criteria.andCreateTimeLessThanOrEqualTo(req.getEndDate());
        }

        return fileInfoMapper.selectByExample(example);
    }

    public int insert(FileInfoPO record) {
        return fileInfoMapper.insertSelective(record);
    }

    public int update(FileInfoPO record) {
        return fileInfoMapper.updateByPrimaryKeySelective(record);
    }
}
